package collector

import (
	"github.com/prometheus/client_golang/prometheus"
	"math/rand"
	"sync"
)
// 定义指标结构体
type Metrics struct {
	metrics map[string]*prometheus.Desc
	mutex  sync.Mutex
}

// 创建指标描述符
func newGlobalMetric(namespace string,metricName string,docString string,labels []string) *prometheus.Desc{
	return prometheus.NewDesc(namespace+"_"+metricName,docString,labels,nil)
}


// 初始化指标信息
func NewMetrics(namespace string) *Metrics{
	return &Metrics{
		metrics: map[string]*prometheus.Desc{
			"my_counter_metric": newGlobalMetric(namespace,"my_counter_metric","the description of my_counter_metric",[]string{"host"}),
			"my_gauage_metric": newGlobalMetric(namespace,"my_gauage_metric","the description of my_gauage_metric",[]string{"host"}),
		},
	}
}

// 实现接口describe,传递接口中的指标描述符到channel
func (c *Metrics)Describe(ch chan<-*prometheus.Desc){
	for _,m := range c.metrics{
		ch <- m
	}
}

// 实现接口collect，抓取最新的数据传递给channel
func (c *Metrics)Collect(ch chan<-prometheus.Metric) {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	mockCounterMetricData,mockGaugeMetricData:=c.GenerateMockData()
	for host,currentValue := range mockCounterMetricData{
		ch <-prometheus.MustNewConstMetric(c.metrics["my_counter_metric"],prometheus.CounterValue,float64(currentValue),host)
	}
	for host,currentValue := range mockGaugeMetricData{
		ch <-prometheus.MustNewConstMetric(c.metrics["my_gauage_metric"],prometheus.GaugeValue,float64(currentValue),host)
	}
}

func (c *Metrics)GenerateMockData()(mockCounterMetricData map[string]int,mockGaugeMetricData map[string]int)  {
	mockCounterMetricData = map[string]int{
		"yahoo.com": int(rand.Int31n(1000)),
		"google": int(rand.Int31n(1000)),

	}
	mockGaugeMetricData = map[string]int{
		"yahoo.com": int(rand.Int31n(10)),
		"google": int(rand.Int31n(10)),

	}
	return
}